package com.baidu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baidu.entity.PageResult;
import com.baidu.entity.Result;
import com.baidu.mapper.RoleMapper;
import com.baidu.pojo.Permission;
import com.baidu.pojo.Role;
import com.baidu.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void addRole(Role role, Integer[] permissionIds) {
        roleMapper.addRole(role);
        setRoleAndPermission(role.getId(),permissionIds);
    }

    @Override
    public Role findRoleById(Integer id) {
        return roleMapper.findRoleById(id);
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page=roleMapper.findPageByQueryString(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void editRole(Role role, Integer[] permissionIds) {
        roleMapper.editRole(role);
        deleteRoleAndPermission(role.getId());
        if(permissionIds!=null&&permissionIds.length>0){
            setRoleAndPermission(role.getId(),permissionIds);
        }
    }

    @Override
    public void deleteRoleById(Integer id) {
        Integer count = findRoleAndPermission(id);
        if(count>0){
            deleteRoleAndPermission(id);
        }
        roleMapper.deleteRoleById(id);
    }


    //建立角色与权限关系
    public void setRoleAndPermission(Integer roleid,Integer[] permissionIds){
        Map<String,Integer> map;
        if(permissionIds!=null){
            for(Integer permissionId:permissionIds){
                map=new HashMap<>();
                map.put("permissionId",permissionId);
                map.put("roleid",roleid);
                roleMapper.setRoleAndPermission(map);
            }
        }
    }

    //解除角色与权限关系
    public void deleteRoleAndPermission(Integer roleid){
        roleMapper.deleteRoleAndPermission(roleid);
    }

    //查找角色与权限关系中是否存在角色ID
    public Integer findRoleAndPermission(Integer roleid){
        return roleMapper.findRoleAndPermission(roleid);
    }


}
